package dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type HeroInfo struct {
	RoleId    int64                        `gorm:"column:roleid;primary"`
	RoleCells datatypes.JSONType[[]string] `gorm:"column:rolecells"`

	Heros      datatypes.JSONType[map[int32]string]   `gorm:"column:heros"`
	HeroSkills datatypes.JSONType[map[int32][]string] `gorm:"column:heroskills"`
	HeroCells  datatypes.JSONType[map[int32][]string] `gorm:"column:herocells"`
}

func (HeroInfo) TableName() string {
	return "hero_info"
}

var (
	all_hero_info_field = zutils.GetGormFields(HeroInfo{})
)

func CreateSqlHeroInfo(obj *HeroInfo) {
	db := mysql.GetServerDBConnection()
	if err := db.Create(obj).Error; err != nil {
		zlog.Errorf("create HeroInfo %v data failed: %v", obj, err)
	}
}

func GetHeroInfo(_roleId int64) *HeroInfo {
	db := mysql.GetServerDBConnection()
	var rstRobot HeroInfo
	if err := db.Select(all_hero_info_field).Where("roleid=?", _roleId).First(&rstRobot).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetHeroInfo ERR!!! id: %d, err: %v", _roleId, err)
		}
		rstRobot = HeroInfo{
			RoleId: _roleId,
		}
		defer func() {
			CreateSqlHeroInfo(&rstRobot)
		}()
	}
	return &rstRobot
}
